﻿using ConfExpert.Forms.Base;
using ConfExpert.Utility;

using DevExpress.XtraPivotGrid;
using DevTeam;

using System;
using System.Drawing;
using System.Windows.Forms;

namespace ConfExpert.Forms.SatinAlma
{
    public partial class Takip2 : XForm
    {
        int CKBatchId = -1;
        public Takip2(int ckBatchId)
        {
            InitializeComponent();
            TAM.CikisPartisiLinesTableAdapter = new Datasets.MyDataTableAdapters.CikisPartisiLinesTableAdapter();

            this.CKBatchId = ckBatchId;
            this.Text += "- " + AppSession.Lookups.CKBatch.FindByCKBatchId(CKBatchId).Notes;
        }

        BindingSource bsUP, bsUPD, bsT, bsT2, bsC;
        private void Takip2_Load(object sender, EventArgs e)
        {

            /*
                Constraint con = ds.xTakip2.Constraints[1];     //DİKKAT! ilki PK diye düşündük..
                if (con is ForeignKeyConstraint)
                    ds.xTakip2.Constraints.Remove(con);
            */
            //ForeignKeyConstraint ParentFK = new ForeignKeyConstraint(rel.ParentColumns, rel.ChildColumns);
            //ParentFK.UpdateRule = Rule.Cascade;
            //rel.ChildTable.Constraints.Add(ParentFK);



            //          DataRelation GA = new DataRelation("FK_xTakip2_xTakip1_PartiNo",
            //new DataColumn[] { ds.xTakip1.Columns["PartiNo"], ds.xTakip1.Columns["AtelyeId"] },
            //new DataColumn[] { ds.xTakip2.Columns["PartiNo"], ds.xTakip2.Columns["AtelyeId"] }
            //);
            //          ds.Relations.Add(GA);

            //          ds.xTakip2.Columns.Add("CikanAdet", typeof(int), "SUM(Child(FK_xTakip3_xTakip2_DosyaNoLinea).CikanAdet)");
            //          ds.xTakip1.Columns.Add("CikanAdet", typeof(int), "SUM(Child(FK_xTakip2_xTakip1_PartiNo).CikanAdet)");



            bsUP = new BindingSource(ds, "xTakip1");
            bsUPD = new BindingSource(bsUP, "FK_xTakip2_xTakip1_PartiNo");
            bsT = new BindingSource(bsUPD, "FK_xTakip3_xTakip2_DosyaNoLinea");

            //ds.xTakip4.Columns.Add("Adet", typeof(int), "ISNULL(CikanAdet, SiparisAdet)");
            bsT2 = new BindingSource(ds, "xTakip4");

            bsC = new BindingSource(ds, "CikisPartisiLines");

            AddBsToList(bsC);
            InitGridView(gridView1, bsUP);
            InitGridView(gridView2, bsUPD);
            InitGridView(gridView3, bsT);

            DrillDownGrid(gridView4, bsT2);
            gridView4.AddSummary("SiparisAdet", "CikanAdet", "YuklenenAdet");
            //gridView1.OptionsBehavior.Editable = false;

            InitPivot(bsT2);

            InitGridView(gridView5, bsC);

            gridView3.Columns["DosyaNo"].Visible = gridView3.Columns["Corpo"].Visible = gridView3.Columns["Modello"].Visible = gridView2.Columns["Gruppo"].Visible = gridView2.Columns["PartiNo"].Visible = gridView2.Columns["AtelyeId"].Visible = false;
            gridView1.OptionsBehavior.Editable = gridView2.OptionsBehavior.Editable = gridView3.OptionsBehavior.Editable = false;

            gridView3.Columns["YuklenenAdet"].OptionsColumn.AllowMerge = gridView3.Columns["CikanAdet"].OptionsColumn.AllowMerge = DevExpress.Utils.DefaultBoolean.False;
            gridView3.Columns["Modello"].OptionsColumn.AllowMerge = DevExpress.Utils.DefaultBoolean.True;
            gridView3.OptionsView.AllowCellMerge = true;
            gridView3.Columns["PRO"].Caption = "Corpo";

            gridView1.FormatAsNumber(0, "CikanAdet");
            gridView2.FormatAsNumber(0, "CikanAdet");
            gridView3.FormatAsNumber(0, "CikanAdet");

            gridView1.AddSummary("CikanAdet");
            gridView2.AddSummary("CikanAdet");
            gridView3.AddSummary("CikanAdet");
            gridView5.AddSummary("CikanAdet", "YuklenenAdet");

            GetDetails("xTakip1;xTakip2;xTakip3;xTakip4;CikisPartisiLines", "GetUretim", CKBatchId);
            pgc.Cells.Selection = new Rectangle(new Point(0, 0), new Size(1, 1));
            pgc.Fields["Modello_1"].BestFit();
            pgc.BestFit();

            gridView1.BestFitColumns();
            gridView2.BestFitColumns();
            gridView3.BestFitColumns();
            gridView4.BestFitColumns();
            gridView5.BestFitColumns();

            btnKaydet.ItemClick += btnKaydet_ItemClick;
            //btnKF.Click += new EventHandler(btnKF_Click);

            GridManager gm3 = GridManager.GetManager(gridView1);
            gm3.GridMenu.AddMenu("Kesim Föyü- TR", btnKF_Click);
            gm3.GridMenu.AddMenu("Kesim Föyü- IT", btnKFIt_Click);
            gm3.GridMenu.AddMenu("Bu execution için kumaş ihtiyacı", KumasIhtiyaci_Click);

            //comboBoxEdit1.SelectedIndexChanged += new EventHandler(comboBoxEdit1_SelectedIndexChanged);
            //comboBoxEdit1.SelectedIndex = 1;
            //comboBoxEdit1.Properties.TextEditStyle = TextEditStyles.DisableTextEditor;

            //RepositoryItemComboBox ri = new RepositoryItemComboBox();
            //ri.TextEditStyle = TextEditStyles.DisableTextEditor;

            xtraTabControl1.SelectedPageChanged += new DevExpress.XtraTab.TabPageChangedEventHandler(xtraTabControl1_SelectedPageChanged);



        }

        void btnKaydet_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Save();
        }

        void btnAlg_Click(object sender, EventArgs e)
        {
            using (EnAzIlave ad = new EnAzIlave(CKBatchId))
            {
                ad.ShowDialog();
            }
        }


        void xtraTabControl1_SelectedPageChanged(object sender, DevExpress.XtraTab.TabPageChangedEventArgs e)
        {
            if (e.Page == xtraTabPage1)
            {
                //labelControl1.Visible = comboBoxEdit1.Visible = 
                btnKaydet.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
            }
            else if (e.Page == xtraTabPage2)
            {
                //labelControl1.Visible = comboBoxEdit1.Visible = true;
                btnKaydet.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
            }
            else if (e.Page == xtraTabPage3)
            {
                //labelControl1.Visible = comboBoxEdit1.Visible = false;
                btnKaydet.Visibility = ytk(78) ? DevExpress.XtraBars.BarItemVisibility.Always : DevExpress.XtraBars.BarItemVisibility.Never;
            }
        }

        void comboBoxEdit1_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (comboBoxEdit1.EditValue.ToInt())
            {
                case 0: adet.FieldName = "SiparisAdet"; break;
                case 1: adet.FieldName = "CikanAdet"; break;
                case 2: adet.FieldName = "YuklenenAdet"; break;
            }
        }


        private PivotGridField AddNewPivotField(PivotGridControl pgc, string FieldName, PivotArea pa)
        {
            PivotGridField fd = new PivotGridField();
            fd.FieldName = fd.Caption = FieldName;
            fd.CellFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
            fd.CellFormat.FormatString = "#,###.##";
            fd.SetAreaPosition(pa, 0);
            pgc.Fields.Add(fd);

            fd.Name = "_" + FieldName;

            if (FieldName.Contains("Ade"))
                fd.Name = "adet";
            return fd;
        }


        //bool PivotInitialized = false;
        void InitPivot(BindingSource bsT2)
        {
            pgc.DataSource = bsT2;

            pgc.OptionsCustomization.CustomizationFormStyle = DevExpress.XtraPivotGrid.Customization.CustomizationFormStyle.Excel2007;
            pgc.CellClick += new PivotCellEventHandler(pivotGridControl1_CellClick);
            pgc.CellSelectionChanged += new EventHandler(pgc_CellSelectionChanged);
            pgc.FocusedCellChanged += new EventHandler(pgc_FocusedCellChanged);
            pgc.FieldValueDisplayText += new PivotFieldDisplayTextEventHandler(pivotGrid_FieldValueDisplayText);
            pgc.CustomAppearance += new PivotCustomAppearanceEventHandler(pivotGridControl1_CustomAppearance);

            RefreshFields();
        }


        void RefreshFields()
        {
            pgc.BeginUpdate();
            pgc.Fields.Clear();

            PivotGridFieldBase[] pgf1 = new PivotGridFieldBase[2];
            pgf1[0] = AddNewPivotField(pgc, "Linea", PivotArea.RowArea);
            pgf1[1] = AddNewPivotField(pgc, "Modello_1", PivotArea.RowArea);
            pgc.Groups.Add(pgf1, "LineaModello");

            PivotGridFieldBase[] pgf2 = new PivotGridFieldBase[2];
            pgf2[0] = AddNewPivotField(pgc, "AtelyeId", PivotArea.ColumnArea);
            ((PivotGridField)pgf2[0]).FieldEdit = RI(Rp.Atelye);
            pgf2[0].ExpandedInFieldsGroup = false;
            pgf2[1] = AddNewPivotField(pgc, "Gruppo", PivotArea.ColumnArea);
            pgc.Groups.Add(pgf2, "GruppoAtelye");

            adet = AddNewPivotField(pgc, "Adet", PivotArea.DataArea);

            //TODO: bu niye çalışmıyor? OA
            //AddNewField(pgc, "Linea", PivotArea.FilterArea);

            //.Width = 40;  .Visible = true;
            //    fld.SummaryType = DevExpress.Data.PivotGrid.PivotSummaryType.Sum;

            foreach (PivotGridField pgf in pgc.Fields)
            {
                pgf.SortOrder = PivotSortOrder.Ascending;
                pgf.Options.AllowSort = DevExpress.Utils.DefaultBoolean.True;
            }
            pgc.EndUpdate();
        }

        PivotGridField adet;
        void pivotGridControl1_CustomAppearance(object sender, PivotCustomAppearanceEventArgs e)
        {
            if (e.Focused)
                e.Appearance.BackColor = e.Appearance.BackColor2 = Color.YellowGreen;   // Color.FromArgb(255, 192, 0);
        }

        void pgc_FocusedCellChanged(object sender, EventArgs e)
        {
            CellChanged();
        }


        void pgc_CellSelectionChanged(object sender, EventArgs e)
        {
            CellChanged();
        }

        private void CellChanged()
        {
            double PivotSum = 0.0;

            if (pgc.Cells.MultiSelection.SelectedCells.Count > 0)
            {
                foreach (Point cell in pgc.Cells.MultiSelection.SelectedCells)
                {
                    DevExpress.XtraPivotGrid.PivotCellEventArgs cellInfo = pgc.Cells.GetCellInfo(cell.X, cell.Y);
                    if (cellInfo.ColumnValueType == DevExpress.XtraPivotGrid.PivotGridValueType.Value &&
                        cellInfo.RowValueType == DevExpress.XtraPivotGrid.PivotGridValueType.Value)
                        PivotSum += Convert.ToDouble(pgc.GetCellValue(cell.X, cell.Y));
                }
            }
            else
            {
                DevExpress.XtraPivotGrid.PivotCellEventArgs cellInfo = pgc.Cells.GetFocusedCellInfo();
                if (cellInfo.ColumnValueType == DevExpress.XtraPivotGrid.PivotGridValueType.Value &&
                    cellInfo.RowValueType == DevExpress.XtraPivotGrid.PivotGridValueType.Value)
                    PivotSum += Convert.ToDouble(pgc.GetCellValue(pgc.Cells.FocusedCell.X, pgc.Cells.FocusedCell.Y));

            }
            //lblPivot.Text = PivotSum == 0 ? string.Empty : String.Format("{0:#,##0.## mt'.'}", PivotSum);
        }

        void pivotGridControl1_CellClick(object sender, DevExpress.XtraPivotGrid.PivotCellEventArgs e)
        {
            gridControl4.DataSource = e.CreateDrillDownDataSource();
            ExpandCollapse(splitContainerControl1, (gridView1.RowCount > 0 ? AcKapa.Expand : AcKapa.Collapse));
            gridView4.BestFitColumns();
            gridView4.MoveFirst();
        }




        void btnKF_Click(object sender, EventArgs e)
        {
            string idxs = string.Empty;
            idxs = GetIdx(idxs);

            //TODO: CikisPartisiId'yi gönder!
            //if (dosyalar != String.Empty)
            //{
            //    xrKesim barcode = new xrKesim(dosyalar, "TR");
            //    barcode.ShowPreview();
            //}
        }

        void btnKFIt_Click(object sender, EventArgs e)
        {
            string idxs = string.Empty;
            idxs = GetIdx(idxs);

            //TODO: CikisPartisiId'yi gönder!
            //if (dosyalar != String.Empty)
            //{
            //    xrKesim barcode = new xrKesim(dosyalar, "IT");
            //    barcode.ShowPreview();
            //}
        }

        void KumasIhtiyaci_Click(object sender, EventArgs e)
        {
            int CikisPartisiId = intParse(bsUP, "CikisPartisiId");

            if (CikisPartisiId > 0)
                using (GP._Need n = new GP._Need(CKBatchId, CikisPartisiId))
                {
                    n.ShowDialog();
                }
        }

        private string GetIdx(string idxs)
        {
            foreach (int rowHandle in gridView1.GetSelectedRows())
                if (rowHandle > -1)
                    idxs += gridView1.GetRowCellValue(rowHandle, "PartiNo").ToString() + ",";

            if (idxs.Substring(idxs.Length - 1, 1) == ",")
                idxs = idxs.Substring(0, idxs.Length - 1);
            return idxs;
        }

        void simpleButton1_Click(object sender, EventArgs e)
        {
            try
            {
                ds.xTakip2.Columns["CikanAdet"].Expression =
                ds.xTakip1.Columns["CikanAdet"].Expression = string.Empty;

                Save();
            }
            finally
            {
                ds.xTakip2.Columns["CikanAdet"].Expression = "SUM(Child(FK_xTakip3_xTakip2_DosyaNoLinea).CikanAdet)";
                ds.xTakip1.Columns["CikanAdet"].Expression = "SUM(Child(FK_xTakip2_xTakip1_PartiNo).CikanAdet)";
            }
        }
    }
}